package com.leetcode.p0;


import com.utils.DataUtils;

public class Test79 {

    int[][] direction = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public boolean exist(char[][] board, String word) {
        boolean[][] visited = new boolean[board.length][board[0].length];

        for (int m = 0; m < board.length; m++) {
            for (int n = 0; n < board[m].length; n++) {
                boolean result = help(board, word, visited, m, n, 0);
                if (result) {
                    return true;
                }
            }
        }

        return false;
    }

    private boolean help(char[][] board, String word, boolean[][] visited, int m, int n, int currentLength) {
        if (board[m][n] != word.charAt(currentLength)) {
            return false;
        }

        if (currentLength == word.length() - 1) {
            return true;
        }

        if (visited[m][n]) {
            return false;
        }

        visited[m][n] = true;

        for (int i = 0; i < direction.length; i++) {
            int nextX = m + direction[i][0];
            int nextY = n + direction[i][1];

            if (nextX >= 0 && nextX < board.length && nextY >= 0 && nextY < board[0].length) {
                if (!visited[nextX][nextY]) {
                    if (help(board, word, visited, nextX, nextY, currentLength + 1)) {
                        return true;
                    }
                }
            }
        }

        visited[m][n] = false;
        return false;
    }

    public static void main(String[] args) {
        Test79 test = new Test79();

        char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};

        DataUtils.printDoubleArrayByChar(board);

        System.out.println(test.exist(board, "ABCCED"));

    }

}
